   // 游戏常量
        var GAME_WIDTH = 800;
        var GAME_HEIGHT = 600;
        var TANK_SIZE = 40;
        var BULLET_SIZE = 4;
        var WALL_SIZE = 40;
        var ENEMY_SPAWN_INTERVAL = 3000;
        var POWER_UP_CHANCE = 0.1;

        // 游戏状态
        var gameState = {
            isPlaying: false,
            score: 0,
            level: 1,
            lives: 3,
            enemiesRemaining: 10,
            maxLevel: 10,
            lastFrameTime: 0,
            lastEnemySpawn: 0,
            background: {
                particles: [],
                grid: {
                    offset: 0,
                    speed: 0.5
                },
                gradient: {
                    angle: 0,
                    speed: 0.2
                }
            },
            player: {
                x: 400,
                y: 550,
                width: TANK_SIZE,
                height: TANK_SIZE,
                speed: 2,
                direction: 'up',
                color: '#0f0',
                isInvincible: false,
                invincibleTimer: 0,
                lastShot: 0,
                shotDelay: 500,
                powerUps: {
                    speed: 0,
                    power: 0
                },
                upgrades: {
                    armor: 0,      // 装甲等级
                    firepower: 0,  // 火力等级
                    engine: 0      // 引擎等级
                },
                specialWeapon: null,  // 特殊武器
                specialWeaponTimer: 0 // 特殊武器持续时间
            },
            bullets: [],
            enemies: [],
            walls: [],
            powerUps: [],
            explosions: [],
            highScores: JSON.parse(localStorage.getItem('tankHighScores')) || [],
            gameStats: JSON.parse(localStorage.getItem('tankGameStats')) || {
                gamesPlayed: 0,
                totalKills: 0,
                totalScore: 0,
                powerUpsCollected: 0,
                levelsCompleted: 0,
                upgradesPurchased: 0,
                shotsFired: 0,
                enemiesDefeated: 0,
                timePlayed: 0,
                highestLevel: 0
            },
            currency: 0  // 游戏货币
        };

        // 添加新的道具类型
        var POWER_UP_TYPES = {
            LIFE: { type: 'life', symbol: '❤️', color: '#f00' },
            SPEED: { type: 'speed', symbol: '⚡', color: '#0f0' },
            POWER: { type: 'power', symbol: '💪', color: '#00f' },
            ARMOR: { type: 'armor', symbol: '🛡️', color: '#ff0' },
            FIREPOWER: { type: 'firepower', symbol: '🔥', color: '#f80' },
            ENGINE: { type: 'engine', symbol: '⚙️', color: '#0ff' },
            SPECIAL: { type: 'special', symbol: '💫', color: '#f0f' }
        };

        // 特殊武器类型
        var SPECIAL_WEAPONS = {
            LASER: {
                name: '激光',
                duration: 5000,
                fireRate: 100,
                damage: 2,
                color: '#f00'
            },
            MISSILE: {
                name: '导弹',
                duration: 3000,
                fireRate: 500,
                damage: 3,
                color: '#ff0'
            },
            SHIELD: {
                name: '护盾',
                duration: 8000,
                color: '#0ff'
            }
        };

        // 对象池
        var objectPool = {
            bullets: [],
            explosions: [],
            
            getBullet: function() {
                if (this.bullets.length > 0) {
                    return this.bullets.pop();
                }
                return {
                    x: 0,
                    y: 0,
                    width: BULLET_SIZE,
                    height: BULLET_SIZE,
                    speed: 10,
                    direction: 'up',
                    owner: null
                };
            },
            
            returnBullet: function(bullet) {
                this.bullets.push(bullet);
            },
            
            getExplosion: function() {
                if (this.explosions.length > 0) {
                    return this.explosions.pop();
                }
                return {
                    x: 0,
                    y: 0,
                    frame: 0
                };
            },
            
            returnExplosion: function(explosion) {
                this.explosions.push(explosion);
            }
        };

        // 获取Canvas上下文
        var canvas = document.getElementById('game-canvas');
        var ctx = canvas.getContext('2d');

        // 游戏主循环
        function gameLoop(timestamp) {
            if (!gameState.isPlaying) return;
            
            if (!gameState.lastFrameTime) {
                gameState.lastFrameTime = timestamp;
            }
            var deltaTime = timestamp - gameState.lastFrameTime;
            gameState.lastFrameTime = timestamp;
            
            // 更新游戏时间统计
            gameState.gameStats.timePlayed += deltaTime / 1000; // 转换为秒
            
            update(deltaTime);
            render();
            
            if (gameState.lives <= 0) {
                endGame(false);
                return;
            }
            
            if (gameState.enemies.length === 0 && gameState.enemiesRemaining === 0) {
                levelComplete();
                return;
            }
            
            requestAnimationFrame(gameLoop);
        }

        // 更新游戏状态
        function update(deltaTime) {
            updateBackground(deltaTime); // 更新背景
            updatePlayer(deltaTime);
            updateBullets(deltaTime);
            updateEnemies(deltaTime);
            updateExplosions(deltaTime);
            updatePowerUps(deltaTime);
            updateInvincibility(deltaTime);
            updateSpecialWeapon(deltaTime);
        }

        // 更新玩家状态
        function updatePlayer(deltaTime) {
            var speed = gameState.player.speed;
            
            switch (gameState.player.direction) {
                case 'up':
                    if (canMove(gameState.player, 0, -speed)) {
                        gameState.player.y -= speed;
                    }
                    break;
                case 'down':
                    if (canMove(gameState.player, 0, speed)) {
                        gameState.player.y += speed;
                    }
                    break;
                case 'left':
                    if (canMove(gameState.player, -speed, 0)) {
                        gameState.player.x -= speed;
                    }
                    break;
                case 'right':
                    if (canMove(gameState.player, speed, 0)) {
                        gameState.player.x += speed;
                    }
                    break;
            }
            
            // 限制玩家在画布范围内
            gameState.player.x = Math.max(40, Math.min(canvas.width - 80, gameState.player.x));
            gameState.player.y = Math.max(40, Math.min(canvas.height - 80, gameState.player.y));
        }

        // 更新子弹状态
        function updateBullets(deltaTime) {
            for (var i = gameState.bullets.length - 1; i >= 0; i--) {
                var bullet = gameState.bullets[i];
                
                switch (bullet.direction) {
                    case 'up':
                        bullet.y -= bullet.speed;
                        break;
                    case 'down':
                        bullet.y += bullet.speed;
                        break;
                    case 'left':
                        bullet.x -= bullet.speed;
                        break;
                    case 'right':
                        bullet.x += bullet.speed;
                        break;
                }
                
                // 检查子弹是否超出边界
                if (bullet.x < 0 || bullet.x > canvas.width || bullet.y < 0 || bullet.y > canvas.height) {
                    objectPool.returnBullet(bullet);
                    gameState.bullets.splice(i, 1);
                    continue;
                }
                
                // 检查子弹碰撞
                var grid = createSpatialHash();
                var cellX = Math.floor(bullet.x / 40);
                var cellY = Math.floor(bullet.y / 40);
                
                var collision = false;
                
                // 检查墙壁碰撞
                for (var x = cellX - 1; x <= cellX + 1; x++) {
                    for (var y = cellY - 1; y <= cellY + 1; y++) {
                        var key = x + ',' + y;
                        if (grid[key]) {
                            for (var j = 0; j < grid[key].length; j++) {
                                var wall = grid[key][j];
                                if (checkCollision(bullet, wall)) {
                                    objectPool.returnBullet(bullet);
                                    gameState.bullets.splice(i, 1);
                                    collision = true;
                                    break;
                                }
                            }
                        }
                        if (collision) break;
                    }
                    if (collision) break;
                }
                
                if (collision) continue;
                
                // 检查敌人碰撞
                if (bullet.owner === gameState.player) {
                    for (var j = gameState.enemies.length - 1; j >= 0; j--) {
                        var enemy = gameState.enemies[j];
                        if (checkCollision(bullet, enemy)) {
                            createExplosion(enemy.x, enemy.y);
                            gameState.enemies.splice(j, 1);
                            gameState.score += 100;
                            gameState.currency += 10;
                            
                            // 更新击杀统计
                            gameState.gameStats.enemiesDefeated++;
                            gameState.gameStats.totalKills++;
                            
                            objectPool.returnBullet(bullet);
                            gameState.bullets.splice(i, 1);
                            break;
                        }
                    }
                }
                
                // 检查玩家碰撞
                if (bullet.owner !== gameState.player && checkCollision(bullet, gameState.player) && !gameState.player.isInvincible) {
                    // 根据装甲等级减少伤害
                    var damage = 1;
                    if (gameState.player.upgrades.armor > 0) {
                        damage = Math.max(0, 1 - gameState.player.upgrades.armor * 0.25);
                    }
                    if (damage > 0) {
                        gameState.lives--;
                        gameState.player.isInvincible = true;
                        gameState.player.invincibleTimer = 2000;
                    }
                    objectPool.returnBullet(bullet);
                    gameState.bullets.splice(i, 1);
                }
            }
        }

        // 更新敌人状态
        function updateEnemies(deltaTime) {
            var now = Date.now();
            
            // 确保游戏开始时就生成敌人
            if (gameState.isPlaying && gameState.enemiesRemaining > 0) {
                // 每2秒生成一个敌人，直到达到当前关卡允许的最大数量
                if (gameState.enemies.length < Math.min(5 + Math.floor(gameState.level / 2), 10) && 
                    now - gameState.lastEnemySpawn > 2000) {
                    
                    var validPosition = false;
                    var x, y;
                    var attempts = 0;
                    
                    while (!validPosition && attempts < 50) {
                        attempts++;
                        // 修改生成位置逻辑，确保敌人在画布范围内
                        x = Math.floor(Math.random() * (canvas.width - 120)) + 60;
                        y = Math.floor(Math.random() * (canvas.height - 120)) + 60;
                        validPosition = true;
                        
                        // 确保不会在玩家附近生成
                        if (Math.abs(x - gameState.player.x) < 200 && Math.abs(y - gameState.player.y) < 200) {
                            validPosition = false;
                            continue;
                        }
                        
                        // 检查是否与墙壁重叠
                        for (var i = 0; i < gameState.walls.length; i++) {
                            if (checkCollision({x: x, y: y, width: 40, height: 40}, gameState.walls[i])) {
                                validPosition = false;
                                break;
                            }
                        }
                        
                        // 检查是否与其他敌人重叠
                        for (var i = 0; i < gameState.enemies.length; i++) {
                            if (checkCollision({x: x, y: y, width: 40, height: 40}, gameState.enemies[i])) {
                                validPosition = false;
                                break;
                            }
                        }
                    }
                    
                    if (validPosition) {
                        var enemy = {
                            x: x,
                            y: y,
                            width: TANK_SIZE,
                            height: TANK_SIZE,
                            speed: 2 + Math.floor(gameState.level / 3),
                            direction: ['up', 'down', 'left', 'right'][Math.floor(Math.random() * 4)],
                            lastMove: now,
                            lastShot: now,
                            shotDelay: 2000 - Math.min(gameState.level * 100, 1000)
                        };
                        gameState.enemies.push(enemy);
                        gameState.enemiesRemaining--;
                        gameState.lastEnemySpawn = now;
                    }
                }
            }
            
            // 更新敌人行为
            for (var i = 0; i < gameState.enemies.length; i++) {
                var enemy = gameState.enemies[i];
                
                // 更智能的敌人AI
                if (now - enemy.lastMove > 1000) {
                    // 计算与玩家的距离
                    var dx = gameState.player.x - enemy.x;
                    var dy = gameState.player.y - enemy.y;
                    
                    // 根据与玩家的位置关系决定移动方向
                    if (Math.abs(dx) > Math.abs(dy)) {
                        enemy.direction = dx > 0 ? 'right' : 'left';
                    } else {
                        enemy.direction = dy > 0 ? 'down' : 'up';
                    }
                    
                    enemy.lastMove = now;
                }
                
                // 移动敌人
                switch (enemy.direction) {
                    case 'up':
                        if (canMove(enemy, 0, -enemy.speed)) {
                            enemy.y -= enemy.speed;
                        }
                        break;
                    case 'down':
                        if (canMove(enemy, 0, enemy.speed)) {
                            enemy.y += enemy.speed;
                        }
                        break;
                    case 'left':
                        if (canMove(enemy, -enemy.speed, 0)) {
                            enemy.x -= enemy.speed;
                        }
                        break;
                    case 'right':
                        if (canMove(enemy, enemy.speed, 0)) {
                            enemy.x += enemy.speed;
                        }
                        break;
                }
                
                // 敌人射击
                if (now - enemy.lastShot > enemy.shotDelay) {
                    var bullet = objectPool.getBullet();
                    bullet.x = enemy.x + enemy.width / 2 - 2;
                    bullet.y = enemy.y + enemy.height / 2 - 2;
                    bullet.direction = enemy.direction;
                    bullet.owner = enemy;
                    gameState.bullets.push(bullet);
                    enemy.lastShot = now;
                }
            }
        }
        
        // 更新爆炸效果
        function updateExplosions(deltaTime) {
            for (var i = gameState.explosions.length - 1; i >= 0; i--) {
                var explosion = gameState.explosions[i];
                explosion.frame++;
                
                if (explosion.frame >= 10) {
                    objectPool.returnExplosion(explosion);
                    gameState.explosions.splice(i, 1);
                }
            }
        }

        // 更新道具
        function updatePowerUps(deltaTime) {
            if (Math.random() < 0.001) {
                var types = Object.values(POWER_UP_TYPES);
                var powerUp = types[Math.floor(Math.random() * types.length)];
                
                var validPosition = false;
                var x, y;
                var attempts = 0;
                
                while (!validPosition && attempts < 50) {
                    attempts++;
                    x = Math.floor(Math.random() * (canvas.width - 120)) + 60;
                    y = Math.floor(Math.random() * (canvas.height - 120)) + 60;
                    validPosition = true;
                    
                    if (Math.abs(x - gameState.player.x) < 100 && Math.abs(y - gameState.player.y) < 100) {
                        validPosition = false;
                        continue;
                    }
                    
                    for (var i = 0; i < gameState.walls.length; i++) {
                        if (checkCollision({x: x, y: y, width: 40, height: 40}, gameState.walls[i])) {
                            validPosition = false;
                            break;
                        }
                    }
                    
                    for (var i = 0; i < gameState.enemies.length; i++) {
                        if (checkCollision({x: x, y: y, width: 40, height: 40}, gameState.enemies[i])) {
                            validPosition = false;
                            break;
                        }
                    }
                    
                    for (var i = 0; i < gameState.powerUps.length; i++) {
                        if (checkCollision({x: x, y: y, width: 40, height: 40}, gameState.powerUps[i])) {
                            validPosition = false;
                            break;
                        }
                    }
                }
                
                if (validPosition) {
                    gameState.powerUps.push({
                        x: x,
                        y: y,
                        type: powerUp.type,
                        symbol: powerUp.symbol,
                        color: powerUp.color,
                        width: 40,
                        height: 40
                    });
                }
            }
            
            // 更新道具状态
            for (var i = gameState.powerUps.length - 1; i >= 0; i--) {
                var powerUp = gameState.powerUps[i];
                
                if (checkCollision(powerUp, gameState.player)) {
                    applyPowerUp(powerUp.type);
                    gameState.powerUps.splice(i, 1);
                }
            }
        }

        // 更新无敌状态
        function updateInvincibility(deltaTime) {
            if (gameState.player.isInvincible) {
                gameState.player.invincibleTimer -= deltaTime;
                
                if (gameState.player.invincibleTimer <= 0) {
                    gameState.player.isInvincible = false;
                }
            }
        }

        // 更新特殊武器状态
        function updateSpecialWeapon(deltaTime) {
            if (gameState.player.specialWeapon) {
                gameState.player.specialWeaponTimer -= deltaTime;
                
                if (gameState.player.specialWeaponTimer <= 0) {
                    gameState.player.specialWeapon = null;
                }
            }
        }

        // 渲染游戏画面
        function render() {
            renderBackground(); // 渲染背景
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            // 绘制墙壁/箱子
            for (var i = 0; i < gameState.walls.length; i++) {
                var wall = gameState.walls[i];
                drawBox(ctx, wall.x, wall.y, wall.width);
            }
            // 绘制玩家坦克
            drawTank(ctx, gameState.player.x, gameState.player.y, gameState.player.width, gameState.player.direction, '#00ff99', true, gameState.player.isInvincible);
            // 绘制玩家升级效果
            if (gameState.player.upgrades.armor > 0) {
                ctx.save();
                ctx.strokeStyle = '#ff0';
                ctx.lineWidth = 2;
                ctx.strokeRect(gameState.player.x - 2, gameState.player.y - 2, gameState.player.width + 4, gameState.player.height + 4);
                ctx.restore();
            }
            // 绘制特殊武器效果
            if (gameState.player.specialWeapon) {
                ctx.save();
                ctx.strokeStyle = gameState.player.specialWeapon.color;
                ctx.lineWidth = 2;
                ctx.beginPath();
                ctx.arc(gameState.player.x + gameState.player.width/2, gameState.player.y + gameState.player.height/2, 30, 0, Math.PI * 2);
                ctx.stroke();
                ctx.restore();
            }
            // 绘制敌人
            for (var i = 0; i < gameState.enemies.length; i++) {
                var enemy = gameState.enemies[i];
                drawTank(ctx, enemy.x, enemy.y, enemy.width, enemy.direction, '#ff4444', false, false);
            }
            // 绘制子弹
            for (var i = 0; i < gameState.bullets.length; i++) {
                var bullet = gameState.bullets[i];
                ctx.fillStyle = bullet.owner === gameState.player ? '#0f0' : '#f00';
                ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
                
                // 添加子弹光晕效果
                ctx.shadowColor = bullet.owner === gameState.player ? '#0f0' : '#f00';
                ctx.shadowBlur = 5;
                ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
                ctx.shadowBlur = 0;
            }
            
            // 绘制道具
            for (var i = 0; i < gameState.powerUps.length; i++) {
                var powerUp = gameState.powerUps[i];
                ctx.fillStyle = powerUp.color;
                ctx.font = '20px Arial';
                ctx.fillText(powerUp.symbol, powerUp.x, powerUp.y + 20);
                
                // 添加道具光晕效果
                ctx.shadowColor = powerUp.color;
                ctx.shadowBlur = 10;
                ctx.fillText(powerUp.symbol, powerUp.x, powerUp.y + 20);
                ctx.shadowBlur = 0;
            }
            
            // 绘制爆炸效果
            for (var i = 0; i < gameState.explosions.length; i++) {
                var explosion = gameState.explosions[i];
                var gradient = ctx.createRadialGradient(
                    explosion.x + 20, explosion.y + 20, 0,
                    explosion.x + 20, explosion.y + 20, explosion.frame * 2
                );
                gradient.addColorStop(0, 'rgba(255, 255, 0, 0.8)');
                gradient.addColorStop(0.5, 'rgba(255, 100, 0, 0.6)');
                gradient.addColorStop(1, 'rgba(255, 0, 0, 0)');
                
                ctx.fillStyle = gradient;
                ctx.beginPath();
                ctx.arc(explosion.x + 20, explosion.y + 20, explosion.frame * 2, 0, Math.PI * 2);
                ctx.fill();
            }
            
            // 绘制游戏状态
            ctx.fillStyle = '#fff';
            ctx.font = '16px Arial';
            ctx.fillText('分数: ' + gameState.score, 10, 20);
            ctx.fillText('关卡: ' + gameState.level, 10, 40);
            ctx.fillText('生命: ' + gameState.lives, 10, 60);
            ctx.fillText('敌人: ' + gameState.enemiesRemaining, 10, 80);
            ctx.fillText('货币: ' + gameState.currency, 10, 100);
            
            // 绘制升级状态
            if (gameState.player.upgrades.armor > 0) {
                ctx.fillText('装甲: ' + gameState.player.upgrades.armor, 10, 120);
            }
            if (gameState.player.upgrades.firepower > 0) {
                ctx.fillText('火力: ' + gameState.player.upgrades.firepower, 10, 140);
            }
            if (gameState.player.upgrades.engine > 0) {
                ctx.fillText('引擎: ' + gameState.player.upgrades.engine, 10, 160);
            }
            
            // 绘制特殊武器状态
            if (gameState.player.specialWeapon) {
                ctx.fillStyle = gameState.player.specialWeapon.color;
                ctx.fillText(gameState.player.specialWeapon.name + ': ' + 
                           Math.ceil(gameState.player.specialWeaponTimer / 1000) + '秒', 10, 180);
            }
        }

        // 初始化背景
        function initBackground() {
            // 初始化粒子
            gameState.background.particles = [];
            for (var i = 0; i < 100; i++) {
                gameState.background.particles.push({
                    x: Math.random() * canvas.width,
                    y: Math.random() * canvas.height,
                    size: Math.random() * 2 + 1,
                    speed: Math.random() * 0.5 + 0.1,
                    opacity: Math.random() * 0.5 + 0.2
                });
            }
        }

        // 更新背景
        function updateBackground(deltaTime) {
            // 更新网格偏移
            gameState.background.grid.offset += gameState.background.grid.speed;
            if (gameState.background.grid.offset >= 40) {
                gameState.background.grid.offset = 0;
            }

            // 更新渐变角度
            gameState.background.gradient.angle += gameState.background.gradient.speed;
            if (gameState.background.gradient.angle >= 360) {
                gameState.background.gradient.angle = 0;
            }

            // 更新粒子
            for (var i = 0; i < gameState.background.particles.length; i++) {
                var particle = gameState.background.particles[i];
                particle.y += particle.speed;
                if (particle.y > canvas.height) {
                    particle.y = 0;
                    particle.x = Math.random() * canvas.width;
                }
            }
        }

        // 渲染背景
        function renderBackground() {
            // 创建渐变背景
            var gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
            gradient.addColorStop(0, '#000033');
            gradient.addColorStop(0.5, '#000066');
            gradient.addColorStop(1, '#000033');
            ctx.fillStyle = gradient;
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // 绘制动态网格
            ctx.strokeStyle = 'rgba(0, 255, 255, 0.1)';
            ctx.lineWidth = 1;
            
            // 水平线
            for (var i = gameState.background.grid.offset; i < canvas.height; i += 40) {
                ctx.beginPath();
                ctx.moveTo(0, i);
                ctx.lineTo(canvas.width, i);
                ctx.stroke();
            }
            
            // 垂直线
            for (var i = gameState.background.grid.offset; i < canvas.width; i += 40) {
                ctx.beginPath();
                ctx.moveTo(i, 0);
                ctx.lineTo(i, canvas.height);
                ctx.stroke();
            }

            // 绘制粒子
            for (var i = 0; i < gameState.background.particles.length; i++) {
                var particle = gameState.background.particles[i];
                ctx.fillStyle = `rgba(0, 255, 255, ${particle.opacity})`;
                ctx.beginPath();
                ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
                ctx.fill();
            }

            // 添加光晕效果
            var glowGradient = ctx.createRadialGradient(
                canvas.width / 2, canvas.height / 2, 0,
                canvas.width / 2, canvas.height / 2, canvas.width / 2
            );
            glowGradient.addColorStop(0, 'rgba(0, 255, 255, 0.1)');
            glowGradient.addColorStop(1, 'rgba(0, 255, 255, 0)');
            ctx.fillStyle = glowGradient;
            ctx.fillRect(0, 0, canvas.width, canvas.height);
        }

        // 游戏控制函数
        function startGame() {
            if (!userManager.currentUser) {
                return;
            }
            
            // 隐藏开始界面
            document.getElementById('start-screen').style.display = 'none';
            
            gameState.isPlaying = true;
            gameState.score = 0;
            gameState.level = 1;
            gameState.lives = 3;
            gameState.enemiesRemaining = 10;
            gameState.player.x = 400;
            gameState.player.y = 550;
            gameState.player.direction = 'up';
            gameState.player.isInvincible = false;
            gameState.player.powerUps = { speed: 0, power: 0 };
            gameState.bullets = [];
            gameState.enemies = [];
            gameState.walls = [];
            gameState.powerUps = [];
            gameState.explosions = [];
            initBackground();
            createLevel();
            requestAnimationFrame(gameLoop);
        }

        // 创建关卡
        function createLevel() {
            gameState.walls = [];
            
            // 创建边界墙
            for (var i = 0; i < canvas.width; i += 40) {
                gameState.walls.push({ x: i, y: 0, width: 40, height: 40 });
                gameState.walls.push({ x: i, y: canvas.height - 40, width: 40, height: 40 });
            }
            
            for (var i = 40; i < canvas.height - 40; i += 40) {
                gameState.walls.push({ x: 0, y: i, width: 40, height: 40 });
                gameState.walls.push({ x: canvas.width - 40, y: i, width: 40, height: 40 });
            }
            
            // 创建随机障碍物
            for (var i = 0; i < 10 + gameState.level * 2; i++) {
                var x = Math.floor(Math.random() * (canvas.width / 40 - 2) + 1) * 40;
                var y = Math.floor(Math.random() * (canvas.height / 40 - 2) + 1) * 40;
                
                // 确保不会在玩家出生点生成障碍物
                if (Math.abs(x - gameState.player.x) > 80 || Math.abs(y - gameState.player.y) > 80) {
                    gameState.walls.push({ x: x, y: y, width: 40, height: 40 });
                }
            }
        }

        // 关卡完成
        function levelComplete() {
            gameState.isPlaying = false; // 暂停游戏
            gameState.level++;
            if (gameState.level > gameState.maxLevel) {
                endGame(true);
                return;
            }
            var modal = document.createElement('div');
            modal.style.position = 'fixed';
            modal.style.top = '0';
            modal.style.left = '0';
            modal.style.width = '100%';
            modal.style.height = '100%';
            modal.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
            modal.style.display = 'flex';
            modal.style.justifyContent = 'center';
            modal.style.alignItems = 'center';
            modal.style.zIndex = '1000';
            
            // 创建内容容器
            var content = document.createElement('div');
            content.style.backgroundColor = '#333';
            content.style.padding = '20px';
            content.style.borderRadius = '10px';
            content.style.textAlign = 'center';
            content.style.color = 'white';
            
            // 创建标题
            var title = document.createElement('h2');
            title.textContent = '关卡 ' + (gameState.level - 1) + ' 完成！';
            title.style.color = '#0f0';
            title.style.marginBottom = '20px';
            
            // 创建分数显示
            var score = document.createElement('p');
            score.textContent = '当前得分: ' + gameState.score;
            score.style.fontSize = '18px';
            score.style.marginBottom = '20px';
            
            // 创建下一关按钮
            var nextLevelButton = document.createElement('button');
            nextLevelButton.textContent = '进入第 ' + gameState.level + ' 关';
            nextLevelButton.style.padding = '10px 20px';
            nextLevelButton.style.backgroundColor = '#0f0';
            nextLevelButton.style.color = 'white';
            nextLevelButton.style.border = 'none';
            nextLevelButton.style.borderRadius = '5px';
            nextLevelButton.style.cursor = 'pointer';
            nextLevelButton.onclick = function() {
                modal.remove();
                gameState.isPlaying = true;
                gameState.enemiesRemaining = 10 + gameState.level * 2;
                gameState.player.x = 400;
                gameState.player.y = 550;
                gameState.player.direction = 'up';
                gameState.bullets = [];
                gameState.enemies = [];
                gameState.powerUps = [];
                gameState.explosions = [];
                createLevel();
                requestAnimationFrame(gameLoop);
            };
            
            // 组装模态框
            content.appendChild(title);
            content.appendChild(score);
            content.appendChild(nextLevelButton);
            modal.appendChild(content);
            
            // 添加到页面
            document.body.appendChild(modal);
        }

        // 游戏结束
        function endGame(victory) {
            gameState.isPlaying = false;
            
            // 更新用户统计
            if (userManager.currentUser) {
                var user = userManager.users[userManager.currentUser];
                user.stats.gamesPlayed++;
                user.stats.totalScore += gameState.score;
                user.stats.highScore = Math.max(user.stats.highScore, gameState.score);
                user.stats.totalKills += gameState.score / 100;
                if (victory) {
                    user.stats.levelsCompleted += gameState.level;
                    user.stats.highestLevel = Math.max(user.stats.highestLevel, gameState.level);
                }
                userManager.updateUserStats(); // 保存更新后的统计数据
            }
            
            // 显示开始界面
            document.getElementById('start-screen').style.display = 'flex';
            
            // 更新统计图表
            updateStatsChart();
            
            // 创建模态框
            var modal = document.createElement('div');
            modal.style.position = 'fixed';
            modal.style.top = '0';
            modal.style.left = '0';
            modal.style.width = '100%';
            modal.style.height = '100%';
            modal.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
            modal.style.display = 'flex';
            modal.style.justifyContent = 'center';
            modal.style.alignItems = 'center';
            modal.style.zIndex = '1000';
            
            // 创建内容容器
            var content = document.createElement('div');
            content.style.backgroundColor = '#333';
            content.style.padding = '20px';
            content.style.borderRadius = '10px';
            content.style.textAlign = 'center';
            content.style.color = 'white';
            
            // 创建标题
            var title = document.createElement('h2');
            title.textContent = victory ? '恭喜通关！' : '游戏结束';
            title.style.color = victory ? '#0f0' : '#f00';
            title.style.marginBottom = '20px';
            
            // 创建分数显示
            var score = document.createElement('p');
            score.textContent = '最终得分: ' + gameState.score;
            score.style.fontSize = '18px';
            score.style.marginBottom = '20px';
            
            // 创建按钮容器
            var buttonContainer = document.createElement('div');
            buttonContainer.style.display = 'flex';
            buttonContainer.style.justifyContent = 'center';
            buttonContainer.style.gap = '10px';
            
            // 创建重新开始按钮
            var restartButton = document.createElement('button');
            restartButton.textContent = '重新开始';
            restartButton.style.padding = '10px 20px';
            restartButton.style.backgroundColor = '#f00';
            restartButton.style.color = 'white';
            restartButton.style.border = 'none';
            restartButton.style.borderRadius = '5px';
            restartButton.style.cursor = 'pointer';
            restartButton.onclick = function() {
                modal.remove();
                startGame();
            };
            
            // 创建返回主菜单按钮
            var menuButton = document.createElement('button');
            menuButton.textContent = '返回主菜单';
            menuButton.style.padding = '10px 20px';
            menuButton.style.backgroundColor = '#444';
            menuButton.style.color = 'white';
            menuButton.style.border = 'none';
            menuButton.style.borderRadius = '5px';
            menuButton.style.cursor = 'pointer';
            menuButton.onclick = function() {
                modal.remove();
                document.getElementById('start-screen').style.display = 'flex';
            };
            
            // 组装模态框
            buttonContainer.appendChild(restartButton);
            buttonContainer.appendChild(menuButton);
            content.appendChild(title);
            content.appendChild(score);
            content.appendChild(buttonContainer);
            modal.appendChild(content);
            
            // 添加到页面
            document.body.appendChild(modal);
            
            // 更新游戏统计
            updateHighScores();
            updateGameStats(victory);
        }

        // 碰撞检测
        function checkCollision(obj1, obj2) {
            return obj1.x < obj2.x + obj2.width &&
                   obj1.x + obj1.width > obj2.x &&
                   obj1.y < obj2.y + obj2.height &&
                   obj1.y + obj1.height > obj2.y;
        }

        // 移动检测
        function canMove(obj, dx, dy) {
            var testObj = {
                x: obj.x + dx,
                y: obj.y + dy,
                width: obj.width,
                height: obj.height
            };
            
            var grid = createSpatialHash();
            var cellX = Math.floor(testObj.x / 40);
            var cellY = Math.floor(testObj.y / 40);
            
            for (var x = cellX - 1; x <= cellX + 1; x++) {
                for (var y = cellY - 1; y <= cellY + 1; y++) {
                    var key = x + ',' + y;
                    if (grid[key]) {
                        for (var i = 0; i < grid[key].length; i++) {
                            if (checkCollision(testObj, grid[key][i])) {
                                return false;
                            }
                        }
                    }
                }
            }
            
            return true;
        }

        // 空间哈希
        function createSpatialHash() {
            var grid = {};
            
            for (var i = 0; i < gameState.walls.length; i++) {
                var wall = gameState.walls[i];
                var cellX = Math.floor(wall.x / 40);
                var cellY = Math.floor(wall.y / 40);
                
                for (var x = cellX - 1; x <= cellX + 1; x++) {
                    for (var y = cellY - 1; y <= cellY + 1; y++) {
                        var key = x + ',' + y;
                        if (!grid[key]) {
                            grid[key] = [];
                        }
                        grid[key].push(wall);
                    }
                }
            }
            
            return grid;
        }

        // 创建爆炸效果
        function createExplosion(x, y) {
            var explosion = objectPool.getExplosion();
            explosion.x = x;
            explosion.y = y;
            explosion.frame = 0;
            gameState.explosions.push(explosion);
        }

        // 应用道具效果
        function applyPowerUp(type) {
            switch (type) {
                case 'life':
                    gameState.lives++;
                    break;
                case 'speed':
                    gameState.player.speed = 3;
                    gameState.player.powerUps.speed = 10000;
                    break;
                case 'power':
                    gameState.player.shotDelay = 200;
                    gameState.player.powerUps.power = 5000;
                    break;
                case 'armor':
                    if (gameState.player.upgrades.armor < 3) {
                        gameState.player.upgrades.armor++;
                        gameState.currency += 100;
                    }
                    break;
                case 'firepower':
                    if (gameState.player.upgrades.firepower < 3) {
                        gameState.player.upgrades.firepower++;
                        gameState.currency += 100;
                    }
                    break;
                case 'engine':
                    if (gameState.player.upgrades.engine < 3) {
                        gameState.player.upgrades.engine++;
                        gameState.currency += 100;
                    }
                    break;
                case 'special':
                    var weapons = Object.keys(SPECIAL_WEAPONS);
                    var weapon = weapons[Math.floor(Math.random() * weapons.length)];
                    gameState.player.specialWeapon = SPECIAL_WEAPONS[weapon];
                    gameState.player.specialWeaponTimer = gameState.player.specialWeapon.duration;
                    break;
            }
            gameState.gameStats.powerUpsCollected++;
        }

        // 更新高分记录
        function updateHighScores() {
            gameState.highScores.push({
                score: gameState.score,
                level: gameState.level,
                date: new Date().toLocaleDateString()
            });
            
            gameState.highScores.sort(function(a, b) {
                return b.score - a.score;
            });
            gameState.highScores = gameState.highScores.slice(0, 10);
            
            localStorage.setItem('tankHighScores', JSON.stringify(gameState.highScores));
        }

        // 更新游戏统计
        function updateGameStats(victory) {
            gameState.gameStats.gamesPlayed++;
            gameState.gameStats.totalKills += gameState.score / 100;
            gameState.gameStats.totalScore += gameState.score;
            
            if (victory) {
                gameState.gameStats.levelsCompleted += gameState.level;
            }
            
            localStorage.setItem('tankGameStats', JSON.stringify(gameState.gameStats));
            updateStatsChart();
        }

        // 更新统计图表
        function updateStatsChart() {
            var chart = echarts.init(document.getElementById('stats-chart'));
            
            var option = {
                title: {
                    text: '游戏统计',
                    textStyle: {
                        color: '#fff'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                legend: {
                    data: ['总分数', '击杀数', '道具收集', '完成关卡'],
                    textStyle: {
                        color: '#fff'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: ['统计'],
                    axisLabel: {
                        color: '#fff'
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        color: '#fff'
                    }
                },
                series: [
                    {
                        name: '总分数',
                        type: 'bar',
                        data: [gameState.gameStats.totalScore],
                        itemStyle: {
                            color: '#00ff00'
                        }
                    },
                    {
                        name: '击杀数',
                        type: 'bar',
                        data: [gameState.gameStats.totalKills],
                        itemStyle: {
                            color: '#ff0000'
                        }
                    },
                    {
                        name: '道具收集',
                        type: 'bar',
                        data: [gameState.gameStats.powerUpsCollected],
                        itemStyle: {
                            color: '#ffff00'
                        }
                    },
                    {
                        name: '完成关卡',
                        type: 'bar',
                        data: [gameState.gameStats.levelsCompleted],
                        itemStyle: {
                            color: '#00ffff'
                        }
                    }
                ]
            };
            
            chart.setOption(option);
            
            // 添加窗口大小改变时的自适应
            window.addEventListener('resize', function() {
                chart.resize();
            });
        }

        // 事件监听
        document.addEventListener('keydown', function(e) {
            if (!gameState.isPlaying) return;
            
            switch (e.key) {
                case 'ArrowUp':
                    gameState.player.direction = 'up';
                    break;
                case 'ArrowDown':
                    gameState.player.direction = 'down';
                    break;
                case 'ArrowLeft':
                    gameState.player.direction = 'left';
                    break;
                case 'ArrowRight':
                    gameState.player.direction = 'right';
                    break;
                case ' ':
                    var now = Date.now();
                    if (now - gameState.player.lastShot >= gameState.player.shotDelay) {
                        var bulletX = gameState.player.x + gameState.player.width / 2 - 2;
                        var bulletY = gameState.player.y + gameState.player.height / 2 - 2;
                        
                        // 更新射击统计
                        gameState.gameStats.shotsFired++;
                        
                        // 根据火力等级发射多个子弹
                        if (gameState.player.upgrades.firepower >= 2) {
                            createBullet(gameState.player, bulletX - 5, bulletY, gameState.player.direction);
                            createBullet(gameState.player, bulletX + 5, bulletY, gameState.player.direction);
                        } else {
                            createBullet(gameState.player, bulletX, bulletY, gameState.player.direction);
                        }
                        
                        gameState.player.lastShot = now;
                    }
                    break;
            }
        });

        // 初始化游戏
        document.getElementById('start-btn').addEventListener('click', startGame);
        document.getElementById('load-btn').addEventListener('click', function() {
            var savedGame = localStorage.getItem('tankGameSave');
            if (savedGame) {
                var gameData = JSON.parse(savedGame);
                Object.assign(gameState, gameData);
                document.getElementById('start-screen').style.display = 'none';
                createLevel();
                requestAnimationFrame(gameLoop);
            }
        });

        // 自动保存游戏
        setInterval(function() {
            if (gameState.isPlaying) {
                localStorage.setItem('tankGameSave', JSON.stringify({
                    score: gameState.score,
                    level: gameState.level,
                    lives: gameState.lives,
                    enemiesRemaining: gameState.enemiesRemaining,
                    player: gameState.player,
                    enemies: gameState.enemies,
                    walls: gameState.walls,
                    powerUps: gameState.powerUps
                }));
            }
        }, 5000);

        // 初始化统计图表
        updateStatsChart();

        // 创建子弹
        function createBullet(owner, x, y, direction) {
            var bullet = objectPool.getBullet();
            bullet.x = x;
            bullet.y = y;
            bullet.direction = direction;
            bullet.owner = owner;
            bullet.damage = 1;
            
            // 根据火力等级增加子弹伤害
            if (owner === gameState.player) {
                bullet.damage = 1 + gameState.player.upgrades.firepower;
            }
            
            gameState.bullets.push(bullet);
        }

        // 用户管理
        var userManager = {
            currentUser: null,
            
            init: function() {
                this.loadUsers();
                this.setupEventListeners();
            },
            
            loadUsers: function() {
                try {
                    var usersData = localStorage.getItem('tankUsers');
                    this.users = usersData ? JSON.parse(usersData) : {};
                    
                    // 确保数据结构正确
                    for (var username in this.users) {
                        if (!this.users[username].stats) {
                            this.users[username].stats = {
                                gamesPlayed: 0,
                                totalScore: 0,
                                highScore: 0,
                                totalKills: 0,
                                levelsCompleted: 0,
                                powerUpsCollected: 0,
                                upgradesPurchased: 0,
                                shotsFired: 0,
                                enemiesDefeated: 0,
                                timePlayed: 0,
                                highestLevel: 0
                            };
                        }
                    }
                } catch (e) {
                    console.error("加载用户数据失败:", e);
                    this.users = {};
                }
            },
            
            saveUsers: function() {
                try {
                    localStorage.setItem('tankUsers', JSON.stringify(this.users));
                } catch (e) {
                    console.error("保存用户数据失败:", e);
                }
            },
            
            register: function(username, password) {
                if (!username || !password) {
                    return { success: false, message: '用户名和密码不能为空' };
                }
                
                if (this.users[username]) {
                    return { success: false, message: '用户名已存在' };
                }
                
                // 为新用户创建初始统计数据
                this.users[username] = {
                    password: password,
                    stats: {
                        gamesPlayed: 0,
                        totalScore: 0,
                        highScore: 0,
                        totalKills: 0,
                        levelsCompleted: 0,
                        powerUpsCollected: 0,
                        upgradesPurchased: 0,
                        shotsFired: 0,
                        enemiesDefeated: 0,
                        timePlayed: 0,
                        highestLevel: 0
                    }
                };
                
                this.saveUsers();
                return { success: true };
            },
            
            login: function(username, password) {
                if (!username || !password) {
                    return { success: false, message: '用户名和密码不能为空' };
                }
                
                if (!this.users[username]) {
                    return { success: false, message: '用户名不存在' };
                }
                
                if (this.users[username].password !== password) {
                    return { success: false, message: '密码错误' };
                }
                
                this.currentUser = username;
                
                // 登录时更新游戏状态中的统计数据
                gameState.gameStats = this.users[username].stats;
                
                return { success: true };
            },
            
            // 更新用户统计数据
            updateUserStats: function() {
                if (this.currentUser && this.users[this.currentUser]) {
                    this.users[this.currentUser].stats = gameState.gameStats;
                    this.saveUsers();
                }
            },
            
            setupEventListeners: function() {
                // 登录表单切换
                document.getElementById('show-register').addEventListener('click', function() {
                    document.getElementById('login-form').style.display = 'none';
                    document.getElementById('register-form').style.display = 'block';
                });
                
                document.getElementById('show-login').addEventListener('click', function() {
                    document.getElementById('register-form').style.display = 'none';
                    document.getElementById('login-form').style.display = 'block';
                });
                
                // 注册按钮
                document.getElementById('register-btn').addEventListener('click', function() {
                    var username = document.getElementById('register-username').value;
                    var password = document.getElementById('register-password').value;
                    var confirm = document.getElementById('register-confirm').value;
                    
                    if (!username || !password) {
                        document.getElementById('register-error').textContent = '请填写所有字段';
                        document.getElementById('register-error').style.display = 'block';
                        return;
                    }
                    
                    if (password !== confirm) {
                        document.getElementById('register-error').textContent = '两次输入的密码不一致';
                        document.getElementById('register-error').style.display = 'block';
                        return;
                    }
                    
                    var result = userManager.register(username, password);
                    if (result.success) {
                        // 清空注册表单
                        document.getElementById('register-username').value = '';
                        document.getElementById('register-password').value = '';
                        document.getElementById('register-confirm').value = '';
                        document.getElementById('register-error').style.display = 'none';
                        
                        // 切换到登录表单
                        document.getElementById('register-form').style.display = 'none';
                        document.getElementById('login-form').style.display = 'block';
                        
                        // 自动填充登录表单的用户名
                        document.getElementById('login-username').value = username;
                        
                        // 显示注册成功消息
                        document.getElementById('login-error').textContent = '注册成功，请登录';
                        document.getElementById('login-error').style.color = '#0f0';
                        document.getElementById('login-error').style.display = 'block';
                        
                        // 3秒后隐藏成功消息
                        setTimeout(function() {
                            document.getElementById('login-error').style.display = 'none';
                        }, 3000);
                    } else {
                        document.getElementById('register-error').textContent = result.message;
                        document.getElementById('register-error').style.display = 'block';
                    }
                });
                
                // 登录按钮
                document.getElementById('login-btn').addEventListener('click', function() {
                    var username = document.getElementById('login-username').value;
                    var password = document.getElementById('login-password').value;
                    
                    if (!username || !password) {
                        document.getElementById('login-error').textContent = '请填写所有字段';
                        document.getElementById('login-error').style.display = 'block';
                        return;
                    }
                    
                    var result = userManager.login(username, password);
                    if (result.success) {
                        document.getElementById('login-container').style.display = 'none';
                        document.getElementById('game-container').style.display = 'block';
                        document.getElementById('start-screen').style.display = 'flex';
                        
                        // 更新开始界面的欢迎信息
                        var welcomeMessage = document.createElement('div');
                        welcomeMessage.style.color = '#00ffff';
                        welcomeMessage.style.fontSize = '24px';
                        welcomeMessage.style.marginBottom = '20px';
                        welcomeMessage.style.textShadow = '0 0 10px #00ffff';
                        welcomeMessage.textContent = '欢迎回来，' + username + '！';
                        
                        // 将欢迎信息插入到标题后面
                        var startScreen = document.getElementById('start-screen');
                        var title = startScreen.querySelector('h1');
                        startScreen.insertBefore(welcomeMessage, title.nextSibling);
                        
                        // 更新统计图表
                        updateStatsChart();
                    } else {
                        document.getElementById('login-error').textContent = result.message;
                        document.getElementById('login-error').style.display = 'block';
                    }
                });
            }
        };

        // 初始化用户管理
        userManager.init();

        // ====== 矢量绘制函数 ======
        function drawTank(ctx, x, y, size, direction, color, isPlayer, isInvincible) {
            ctx.save();
            ctx.translate(x + size/2, y + size/2);
            // 旋转到坦克朝向
            var angle = 0;
            switch(direction) {
                case 'up': angle = 0; break;
                case 'down': angle = Math.PI; break;
                case 'left': angle = -Math.PI/2; break;
                case 'right': angle = Math.PI/2; break;
            }
            ctx.rotate(angle);

            // 车身渐变
            var grad = ctx.createLinearGradient(-size/2, -size/2, size/2, size/2);
            grad.addColorStop(0, color);
            grad.addColorStop(1, '#222');
            ctx.fillStyle = isInvincible ? 'rgba(0,255,0,0.5)' : grad;
            ctx.strokeStyle = '#fff';
            ctx.lineWidth = 2;
            ctx.shadowColor = '#000';
            ctx.shadowBlur = 8;
            ctx.fillRect(-size/2, -size/2, size, size);
            ctx.shadowBlur = 0;
            ctx.strokeRect(-size/2, -size/2, size, size);

            // 炮塔
            ctx.beginPath();
            ctx.arc(0, 0, size/4, 0, Math.PI*2);
            ctx.fillStyle = isPlayer ? '#aaf' : '#faa';
            ctx.shadowColor = '#fff';
            ctx.shadowBlur = 8;
            ctx.fill();

            // 炮管
            ctx.shadowBlur = 0;
            ctx.fillStyle = '#bbb';
            ctx.fillRect(0, -size/12, size/2, size/6);

            ctx.restore();
        }

        function drawBox(ctx, x, y, size) {
            ctx.save();
            // 立体渐变
            var grad = ctx.createLinearGradient(x, y, x+size, y+size);
            grad.addColorStop(0, '#c96');
            grad.addColorStop(1, '#654321');
            ctx.fillStyle = grad;
            ctx.strokeStyle = '#fff';
            ctx.lineWidth = 2;
            ctx.shadowColor = '#000';
            ctx.shadowBlur = 6;
            ctx.fillRect(x, y, size, size);
            ctx.shadowBlur = 0;
            ctx.strokeRect(x, y, size, size);
            // 箱子装饰线
            ctx.beginPath();
            ctx.moveTo(x, y+size/2);
            ctx.lineTo(x+size, y+size/2);
            ctx.moveTo(x+size/2, y);
            ctx.lineTo(x+size/2, y+size);
            ctx.strokeStyle = '#fff8';
            ctx.lineWidth = 1;
            ctx.stroke();
            ctx.restore();
        }

